package edu.gxmzu.task.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @ClassName CommonController
 * @Description //TODO
 * @Author cool
 * @Date 2024/12/5 14:10
 * @Version 1.0
 **/

@Tag(name="文件模块")
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {

    //图片访问
    @Operation(summary="访问图片",description = "获取图片信息，name=图片名称 http://localhost:8011/api/common/download?name=ac78d023-6692-44ce-b8dd-0fc4114e5f49.jpg")
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        try {
            String projectPath = System.getProperty("user.dir");
            String filesPath = projectPath + File.separator + "WEB-INF" + File.separator + "files";
            String filesRealPath = filesPath + File.separator;
            //输入流,通过输入流读取文件内容
            FileInputStream fileInputStream = new FileInputStream(new File(filesRealPath+name));

            //输出流,通过输出流将文件写回浏览器,在浏览器展示图片
            ServletOutputStream outputStream = response.getOutputStream();

            //设置一下为图片文件
            response.setContentType("image/jpeg");

            // 输入流读取到 内容放到 bytes数组中
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1){   //当为-1的时候输入流读取完成
                outputStream.write(bytes,0,len);          //写输入流到浏览器
                outputStream.flush();
            }

            //关闭资源
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
